package algorithm.middle;

import pojo.ListNode;

public class GameOfLife289 {
    public void gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = getValue(i, j, board);
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = calculate(board[i][j]);
            }
        }
    }

    /**
     * 根据周围的值，设置当前值
     * 周围有活细胞，则+10
     */
    private int getValue(int i, int j, int[][] board) {
        int res = board[i][j];
        for (int k = -1; k <= 1; k++) {
            for (int l = -1; l <= 1; l++) {
                if (k == 0 && l == 0) {
                    continue;
                }
                int x = i + k;
                int y = j + l;
                //合法单元格
                if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) {
                    //活细胞
                    if (board[x][y] % 10 == 1) {
                        res += 10;
                    }
                }
            }
        }
        return res;
    }


    private int calculate(int value) {
        int source = value % 10;
        int num = value / 10;
        if (source == 1) {
            if (num < 2) {
                return 0;
            }
            if (num <= 3) {
                return 1;
            }
            return 0;
        } else {
            if (num == 3) {
                return 1;
            }
        }
        return 0;
    }
}
